using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Urbania.Utilities;
using Urbania.World;
using Urbania.GUI.Elements;
using Urbania.GUI;

namespace Urbania.Components
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class WorldComponent : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private SpriteBatch spriteBatch;
        private World.World world;
        private Utilities.Camera camera;
        public static GUI.GUIContainer container;
        UserStats userStats;
        HUD hud;

        public WorldComponent(Game game)
            : base(game)
        {
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            world = new World.World(150, 150);
            userStats = UserStats.GetUserStats();
            userStats.Gold = 5000;
            userStats.BureaucracyPoints = 20;
            Button.screen = false;
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Utilities.Loader.LoadTex("Tiles\\Factory");
            Utilities.Loader.LoadTex("Tiles\\Hexagon");
            Utilities.Loader.LoadFont("Font\\menuFont");
            Utilities.Loader.LoadFont("Font\\HUDFont");
            container = new GUI.GUIContainer();
            camera = new Utilities.Camera(world.HomePositionWorld, world, GraphicsDevice);

            hud = new HUD(
                new HUDElement(spriteBatch, new Vector2(5, 5)),//happy
                new HUDElement(spriteBatch, new Vector2(3 * (Game.GraphicsDevice.Viewport.Width) / 4, 5)),//score
                new HUDElement(spriteBatch, new Vector2(2 * (Game.GraphicsDevice.Viewport.Width) / 4, 5)),//money
                new HUDElement(spriteBatch, new Vector2(Game.GraphicsDevice.Viewport.Width / 4, 5)),//approval
                new HUDElement(spriteBatch, new Vector2(2 * (Game.GraphicsDevice.Viewport.Width) / 4, Game.GraphicsDevice.Viewport.Height - 25)),//pollution
                new HUDElement(spriteBatch, new Vector2(Game.GraphicsDevice.Viewport.Width / 4, Game.GraphicsDevice.Viewport.Height - 25)),//bureaucracy
                new HUDElement(spriteBatch, new Vector2(5, Game.GraphicsDevice.Viewport.Height - 25)),//food
                new HUDElement(spriteBatch, new Vector2(3 * (Game.GraphicsDevice.Viewport.Width) / 4, Game.GraphicsDevice.Viewport.Height - 25)),//population
                new HUDElement(spriteBatch, new Vector2(0, Game.GraphicsDevice.Viewport.Height - 25)),
                new HUDElement(spriteBatch, new Vector2(0, 0))
                );
            userStats = UserStats.GetUserStats();

            Game1.lua.Register("ChangeTileType", world, world.GetType().GetMethod("ChangeTileTypeByIndex"));
            container.AddFrame(new Frame(ref Program.lua));
            base.LoadContent();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 
        public int secondsRemaining = 100;
        private int elapsedTime = 0;
        public override void Update(GameTime gameTime)
        {
            
            world.Update(gameTime, camera);
            camera.Update();
            //hud.updateHUD(camera);
            container.Update(gameTime);

            if (MouseWrap.wasReleased(MouseWrap.RightClick))
            {
                RightClickMenu rcm = new RightClickMenu(MouseWrap.PositionWorld, Color.Blue, MenuType.Regular);
                rcm.Generate(world.GetTileUnderMouse());
                container.AddMenu(rcm);
            }

            elapsedTime += gameTime.ElapsedGameTime.Milliseconds;
            if (elapsedTime >= 1000)
            {
                Console.WriteLine(userStats.Happiness);
                secondsRemaining--;
                elapsedTime = 0;
                secondsRemaining = (int)MathHelper.Clamp(secondsRemaining, 0, 100);
                if (secondsRemaining == 0)
                {
                    if (!TheElection())
                    {
                        Game.Exit();
                    }
                    else
                    {
                        secondsRemaining = 100;
                    }
                }
                userStats.BureaucracyPoints += 0.5;
            }

            box.Update(gameTime);
            Utilities.MouseWrap.Update(GraphicsDevice, camera);

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin(
                SpriteSortMode.Immediate,
                BlendState.AlphaBlend,
                camera.GetSamplerForZoomLevel(),
                null,
                null,
                null,
                camera.Transform);


            world.Draw(gameTime, spriteBatch);
            container.Draw(gameTime, spriteBatch);

            spriteBatch.End();

            spriteBatch.Begin();

            hud.Draw("Score: " + ((int)userStats.calculateScore((float)gameTime.TotalGameTime.TotalMilliseconds)).ToString(),
                "Money: " + Math.Floor(userStats.Gold),
                "Pollution: " + ((int)userStats.Pollution).ToString(),
                "Bureaucracy Pts: " + ((int)userStats.BureaucracyPoints).ToString(),
                "Food: " + ((int)userStats.Food).ToString(),
                Loader.getDefaultTex(), //Texture2D happySpriteImage,
                "Approval:" + ((int)userStats.calculateAproval()).ToString(),//Texture2D approvalSpriteImage
                "Time To Election: " + secondsRemaining.ToString(),
                Loader.getDefaultTex()
                );

            spriteBatch.End();

            base.Draw(gameTime);
        }

        public bool TheElection()
        {
            Random r = new Random();
            int chanceToWin = r.Next(100);
            if (chanceToWin > userStats.calculateAproval())
            {
                return false;
            }
            return true;
        }


    }
}
